<template>
  <div class="apple-style-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">员工管理</h1>
    </div>
    
    <!-- 搜索和操作区域 -->
    <div class="action-section">
      <div class="action-buttons">
        <el-button class="apple-button add-button" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加
        </el-button>
        <el-button class="apple-button delete-button" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <el-button class="apple-button" @click="handleExport">
          <el-icon><Download /></el-icon>导出
        </el-button>
        <el-button class="apple-button" @click="handleImportClick">
          <el-icon><Upload /></el-icon>导入
        </el-button>
        <el-button class="apple-button" @click="fetchEmployeeList">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">员工总数</div>
          <div class="stat-value">{{ total }}</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon><UserFilled /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">管理员</div>
          <div class="stat-value">{{ getAdminCount() }}</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon><Service /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">普通客服</div>
          <div class="stat-value">{{ getNormalUserCount() }}</div>
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="employeeList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :header-cell-style="headerCellStyle"
        :cell-style="cellStyle"
        highlight-current-row
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="employee_id" label="工号" min-width="100">
          <template #default="scope">
            <span class="id-cell">{{ scope.row.employee_id }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="100">
          <template #default="scope">
            <div class="username-cell">{{ scope.row.username }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="电子邮箱" min-width="150">
          <template #default="scope">
            <div class="email-cell">{{ scope.row.email }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" min-width="100">
          <template #default="scope">
            <div class="nickname-cell">{{ scope.row.nickname }}</div>
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.role === 1 ? 'danger' : 'primary'"
              effect="light"
              class="role-tag"
            >
              {{ getRoleName(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone_number" label="手机号码" min-width="120">
          <template #default="scope">
            <div class="phone-cell">{{ scope.row.phone_number }}</div>
          </template>
        </el-table-column>
        <el-table-column label="参与提成计算" min-width="120">
          <template #default="scope">
            <el-tag
              :type="getCommissionCalcValue(scope.row.is_commission_calc) === 1 ? 'success' : 'info'"
              effect="light"
              class="commission-tag"
            >
              {{ getCommissionCalcValue(scope.row.is_commission_calc) === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              class="action-button"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              class="action-button"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              class="action-button"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </div>

    <!-- 添加/编辑员工对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加员工' : '编辑员工'"
      width="500px"
      class="apple-dialog"
    >
      <el-form
        ref="employeeFormRef"
        :model="employeeForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="employeeForm.username" :disabled="dialogType === 'edit'" class="apple-input" />
        </el-form-item>
        <el-form-item label="工号" prop="employee_id">
          <el-input v-model="employeeForm.employee_id" placeholder="员工工号，可自定义修改" class="apple-input" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="employeeForm.nickname" class="apple-input" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="employeeForm.email" class="apple-input" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone_number">
          <el-input v-model="employeeForm.phone_number" class="apple-input" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="employeeForm.role" placeholder="请选择角色" class="apple-select">
            <el-option label="普通客服" :value="0" />
            <el-option label="管理员" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="参与提成计算" prop="is_commission_calc">
          <el-select v-model="employeeForm.is_commission_calc" placeholder="请选择是否参与提成计算" class="apple-select" @change="handleCommissionCalcChange">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="pwd">
          <el-input v-model="employeeForm.pwd" type="password" show-password class="apple-input" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'edit'" label="重置密码">
          <el-switch v-model="resetPassword" class="apple-switch" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'edit' && resetPassword" label="新密码" prop="newPwd">
          <el-input v-model="employeeForm.newPwd" type="password" show-password class="apple-input" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" class="apple-button-secondary">取消</el-button>
          <el-button type="primary" @click="submitForm" class="apple-button-primary">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看员工对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="员工详情"
      width="500px"
      class="apple-dialog"
    >
      <div class="detail-card">
        <div class="detail-avatar">
          <el-icon size="48"><Avatar /></el-icon>
        </div>
        <div class="detail-info">
          <h2 class="detail-name">{{ employeeDetail.nickname }}</h2>
          <div class="detail-role">
            <el-tag :type="employeeDetail.role === 1 ? 'danger' : 'primary'" effect="light" class="role-tag">
              {{ getRoleName(employeeDetail.role) }}
            </el-tag>
          </div>
        </div>
      </div>
      <el-descriptions :column="1" border class="detail-descriptions">
        <el-descriptions-item label="用户名">
          <span class="detail-value">{{ employeeDetail.username }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="工号">
          <span class="detail-value">{{ employeeDetail.employee_id }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="电子邮箱">
          <span class="detail-value email-value">{{ employeeDetail.email }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="手机号码">
          <span class="detail-value">{{ employeeDetail.phone_number }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="参与提成计算">
          <el-tag :type="getCommissionCalcValue(employeeDetail.is_commission_calc) === 1 ? 'success' : 'info'" effect="light">
            {{ getCommissionCalcValue(employeeDetail.is_commission_calc) === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 导入员工对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入员工数据"
      width="900px"
      append-to-body
      destroy-on-close
      class="apple-dialog import-dialog"
    >
      <div class="import-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="template-download">
              <h4>下载导入模板</h4>
              <p>请先下载导入模板，按照模板格式填写员工数据后再进行导入：</p>
              <el-button type="primary" @click="downloadTemplate" class="apple-button primary-button">下载导入模板</el-button>
            </div>
            
            <el-divider></el-divider>
            
            <div class="upload-section">
              <h4>文件上传</h4>
              <el-upload
                class="upload-box"
                drag
                action="#"
                :http-request="handleFileUpload"
                :show-file-list="true"
                :limit="1"
                :multiple="false"
                :auto-upload="true"
                accept=".xlsx,.xls,.csv"
                ref="uploadRef"
              >
                <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或 <em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传Excel文件（.xlsx或.xls格式）或CSV文件（.csv格式）
                  </div>
                </template>
              </el-upload>

            </div>
          </el-col>
          <el-col :span="16">
            <div class="import-format-container">
              <h4>导入格式说明</h4>
              <div class="import-format-tips">
                <p><strong>必填字段：</strong>用户名、昵称、电子邮箱、手机号码、角色、密码</p>
                <p><strong>选填字段：</strong>工号、参与提成计算</p>
                <p><strong>字段格式要求：</strong></p>
                <ul>
                  <li><b>用户名</b>：用户登录账号，必须唯一，2-20个字符</li>
                  <li><b>工号</b>：员工工号，如不填写系统将自动生成，最长20个字符</li>
                  <li><b>昵称</b>：用户显示名称，2-20个字符</li>
                  <li><b>电子邮箱</b>：必须是有效的电子邮箱格式</li>
                  <li><b>手机号码</b>：必须是有效的手机号码格式</li>
                  <li><b>角色</b>：必须是以下值之一：普通客服、管理员</li>
                  <li><b>密码</b>：6-20个字符</li>
                  <li><b>参与提成计算</b>：填写"是"或"否"，默认为"是"</li>
                </ul>
                <p><strong>注意事项：</strong></p>
                <ul>
                  <li>如果导入的用户名已存在，将会更新该用户的其他信息</li>
                  <li>批量导入时请确保Excel文件中的所有员工数据格式正确</li>
                  <li>手机号码和电子邮箱将用于系统通知，请确保正确</li>
                </ul>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <el-button @click="importDialogVisible = false" class="apple-button-secondary">取消</el-button>
        <el-button type="primary" @click="submitImport" :loading="importLoading" class="apple-button-primary">开始导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Download, 
  Delete, 
  Refresh, 
  User, 
  UserFilled, 
  Service,
  Avatar,
  Upload,
  UploadFilled
} from '@element-plus/icons-vue'
import { 
  getUserList, 
  createUser, 
  updateUser, 
  deleteUser, 
  batchDeleteUsers, 
  exportUsers,
  importUsers
} from '@/api/users'

// 表格数据
const loading = ref(false)
const employeeList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  username: '',
  nickname: '',
  email: '',
  role: '',
  phone_number: ''
})

// 员工表单
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const employeeFormRef = ref(null)
const employeeForm = reactive({
  id: '',
  username: '',
  employee_id: '',
  nickname: '',
  email: '',
  phone_number: '',
  role: 0,
  pwd: '',
  newPwd: '',
  is_commission_calc: 1
})

// 查看员工详情
const viewDialogVisible = ref(false)
const employeeDetail = reactive({
  username: '',
  employee_id: '',
  nickname: '',
  email: '',
  phone_number: '',
  role: 0,
  is_commission_calc: 1
})

// 是否重置密码
const resetPassword = ref(false)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  employee_id: [
    { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone_number: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 表格样式
const headerCellStyle = () => {
  return {
    background: '#f5f7fa',
    color: '#606266',
    fontWeight: 600,
    fontSize: '14px',
    height: '50px',
    padding: '0 12px'
  }
}

const cellStyle = () => {
  return {
    fontSize: '14px',
    padding: '12px'
  }
}

// 获取管理员数量
const getAdminCount = () => {
  return employeeList.value.filter(item => item.role === 1).length
}

// 获取普通客服数量
const getNormalUserCount = () => {
  return employeeList.value.filter(item => item.role === 0).length
}

// 初始化数据
onMounted(() => {
  console.log('员工管理组件加载')
  fetchEmployeeList()
})

// 初始化阶段，确保employeeList数据正确处理
const processEmployeeData = (data) => {
  if (!data || !Array.isArray(data)) return [];
  
  return data.map(item => {
    const processedItem = { ...item };
    // 确保is_commission_calc是数字类型
    if (Object.prototype.hasOwnProperty.call(processedItem, 'is_commission_calc')) {
      processedItem.is_commission_calc = getCommissionCalcValue(processedItem.is_commission_calc);
    }
    return processedItem;
  });
};

// 获取员工列表
const fetchEmployeeList = async () => {
  loading.value = true
  
  try {
    // 准备查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 调用API获取员工列表
    const response = await getUserList(params)
    
    // 处理响应数据
    if (response && response.data) {
      employeeList.value = processEmployeeData(response.data.items || []);
      total.value = response.data.total || 0
      console.log('成功获取员工列表数据')
    } else {
      employeeList.value = []
      total.value = 0
      ElMessage.warning('获取员工列表数据为空')
    }
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败: ' + (error?.message || '未知错误'))
    employeeList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 添加员工
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 查看员工详情
const handleView = (row) => {
  Object.keys(employeeDetail).forEach(key => {
    employeeDetail[key] = row[key]
  })
  viewDialogVisible.value = true
}

// 编辑员工
const handleEdit = (row) => {
  dialogType.value = 'edit'
  resetForm()
  Object.keys(employeeForm).forEach(key => {
    if (key !== 'pwd' && key !== 'newPwd' && row[key] !== undefined) {
      // 对is_commission_calc字段特殊处理
      if (key === 'is_commission_calc') {
        employeeForm[key] = getCommissionCalcValue(row[key]);
      } else {
        employeeForm[key] = row[key];
      }
    }
  })
  resetPassword.value = false
  dialogVisible.value = true
}

// 删除员工
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除员工 ${row.nickname || row.username} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      await deleteUser(row.id)
      ElMessage.success('删除员工成功')
      fetchEmployeeList() // 刷新列表
    } catch (error) {
      console.error('删除员工失败:', error)
      ElMessage.error('删除员工失败: ' + (error?.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 导出员工
const handleExport = async () => {
  try {
    loading.value = true
    const response = await exportUsers(searchForm)
    
    // 创建一个Blob对象
    const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
    
    // 创建下载链接并点击
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = '员工数据.xlsx'
    link.click()
    
    // 释放URL对象
    URL.revokeObjectURL(link.href)
    
    ElMessage.success('导出员工数据成功')
  } catch (error) {
    console.error('导出员工失败:', error)
    ElMessage.error('导出员工失败: ' + (error?.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 批量选择变更
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 分页大小变更
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchEmployeeList()
}

// 当前页变更
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchEmployeeList()
}

// 提交表单
const submitForm = async () => {
  if (!employeeFormRef.value) return

  employeeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        
        // 确保提交前is_commission_calc为数字类型
        const submitData = { ...employeeForm };
        submitData.is_commission_calc = Number(submitData.is_commission_calc);
        
        if (dialogType.value === 'add') {
          // 创建新用户
          await createUser(submitData)
          ElMessage.success('添加员工成功')
        } else {
          // 更新用户，如果勾选了重置密码，则添加新密码
          if (resetPassword.value) {
            submitData.pwd = submitData.newPwd
          }
          delete submitData.newPwd // 删除临时字段
          
          await updateUser(submitData.id, submitData)
          ElMessage.success('更新员工成功')
        }
        
        dialogVisible.value = false
        fetchEmployeeList() // 刷新列表
      } catch (error) {
        console.error('保存员工失败:', error)
        ElMessage.error('保存员工失败: ' + (error?.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (employeeFormRef.value) {
    employeeFormRef.value.resetFields()
  }
  
  Object.keys(employeeForm).forEach(key => {
    if (key === 'role') {
      employeeForm[key] = 0
    } else if (key === 'is_commission_calc') {
      employeeForm[key] = 1
    } else {
      employeeForm[key] = ''
    }
  })
}

// 获取角色名称
const getRoleName = (role) => {
  const roles = {
    0: '普通客服',
    1: '管理员'
  }
  return roles[role] || '未知角色'
}

// 处理参与提成计算值，确保数据类型一致并正确显示
const getCommissionCalcValue = (value) => {
  // 转换为数字类型进行比较
  const numValue = Number(value);
  // 如果是0或1，直接返回该值
  if (numValue === 0 || numValue === 1) {
    return numValue;
  }
  // 如果是字符串"是"，返回1；如果是字符串"否"，返回0
  if (value === '是') return 1;
  if (value === '否') return 0;
  // 默认返回1 (参与提成计算)
  return 1;
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择需要删除的员工')
    return
  }
  
  const names = selectedRows.value.map(row => row.nickname || row.username).join('、')
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个员工吗？\n${names}`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      const ids = selectedRows.value.map(row => row.id)
      await batchDeleteUsers(ids)
      ElMessage.success('批量删除员工成功')
      fetchEmployeeList() // 刷新列表
    } catch (error) {
      console.error('批量删除员工失败:', error)
      ElMessage.error('批量删除员工失败: ' + (error?.message || '未知错误'))
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 导入相关
const importDialogVisible = ref(false)
const importLoading = ref(false)
const uploadRef = ref(null)
const importFile = ref(null)

// 打开导入对话框
const handleImportClick = () => {
  importDialogVisible.value = true
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
  importFile.value = null
}

// 处理文件上传
const handleFileUpload = (options) => {
  console.log('文件上传处理函数被调用', options)
  
  // 获取文件对象
  const file = options.file
  if (!file) {
    ElMessage.error('请选择文件')
    return
  }
  
  // 文件类型检查
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return
  }
  
  // 文件大小检查（限制10MB）
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!')
    return
  }
  
  // 保存文件引用
  importFile.value = file
  console.log('文件已保存到importFile变量', importFile.value)
  ElMessage.success('文件已选择: ' + file.name)
  
  // 告诉el-upload组件上传成功
  options.onSuccess()
}

// 下载导入模板
const downloadTemplate = () => {
  importLoading.value = true
  
  try {
    // 创建CSV内容
    const headers = ['用户名', '工号', '昵称', '电子邮箱', '手机号码', '角色', '密码', '参与提成计算']
    const rows = [
      headers.join(','),
      ['example_user1', 'EMP001', '示例用户1', 'user1@example.com', '13800138001', '普通客服', 'password123', '是'].join(','),
      ['example_admin', 'EMP002', '管理员示例', 'admin@example.com', '13900139001', '管理员', 'admin123456', '否'].join(','),
      '',
      '说明：用户名、昵称、电子邮箱、手机号码、角色、密码为必填项，工号、参与提成计算为选填项',
      '用户名：登录账号，必须唯一，2-20个字符',
      '工号：员工工号，如不填写系统将自动生成，最长20个字符',
      '角色：只能填写"普通客服"或"管理员"',
      '密码：长度为6-20个字符',
      '参与提成计算：填写"是"或"否"，默认为"是"'
    ]
    
    const csvContent = '\ufeff' + rows.join('\n') // 添加BOM标记，解决中文乱码问题
    
    // 创建Blob对象
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    
    // 创建下载链接并点击
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = '员工导入模板.csv'
    link.click()
    
    // 释放URL对象
    URL.revokeObjectURL(link.href)
    
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('生成模板失败:', error)
    ElMessage.error('生成模板失败: ' + (error?.message || '未知错误'))
  } finally {
    importLoading.value = false
  }
}

// 提交导入文件
const submitImport = () => {
  console.log('提交导入，检查文件:', importFile.value)
  
  // 检查是否有上传文件
  const hasUploadFiles = uploadRef.value && uploadRef.value.uploadFiles && uploadRef.value.uploadFiles.length > 0
  console.log('是否有上传文件:', hasUploadFiles)
  
  // 如果没有找到文件，显示错误提示
  if (!hasUploadFiles && !importFile.value) {
    ElMessage.error('请先选择文件')
    return
  }
  
  // 准备要上传的文件
  let fileToUpload = null
  
  // 优先使用upload组件中的文件
  if (hasUploadFiles) {
    fileToUpload = uploadRef.value.uploadFiles[0].raw
    console.log('使用上传组件中的文件:', fileToUpload ? fileToUpload.name : 'undefined')
  }
  
  // 如果upload组件中没有文件，则使用直接保存的文件引用
  if (!fileToUpload && importFile.value) {
    fileToUpload = importFile.value
    console.log('使用备用文件引用:', fileToUpload.name)
  }
  
  // 最终确认是否有文件可上传
  if (!fileToUpload) {
    ElMessage.error('无法获取文件对象，请重新选择文件')
    return
  }
  
  // 检查文件类型和大小
  const isExcel = 
    fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
    fileToUpload.type === 'application/vnd.ms-excel' ||
    fileToUpload.name.endsWith('.xlsx') ||
    fileToUpload.name.endsWith('.xls') ||
    fileToUpload.name.endsWith('.csv')
    
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件(.xlsx/.xls)或CSV文件(.csv)')
    return
  }
  
  // 文件大小检查（限制20MB）
  const isLt20M = fileToUpload.size / 1024 / 1024 < 20
  if (!isLt20M) {
    ElMessage.error('文件大小不能超过20MB!')
    return
  }
  
  importLoading.value = true
  ElMessage.info('正在上传并处理文件，请稍候...')
  console.log('开始导入文件:', fileToUpload.name)
  
  // 使用导入API
  importUsers(fileToUpload)
    .then(response => {
      console.log('导入响应:', response)
      let responseData = response
      
      // 尝试处理不同的响应格式
      if (response && response.data) {
        responseData = response.data
      }
      
      if (responseData.success || responseData.code === 200) {
        ElMessage.success(responseData.message || '导入成功')
        
        // 如果有错误信息，也显示出来
        if (responseData.errors && responseData.errors.length > 0) {
          const errorMsg = responseData.errors.join('\n')
          // 使用对话框显示详细错误
          ElMessageBox.alert(errorMsg, '部分数据导入失败', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
        
        // 导入成功后刷新列表
        fetchEmployeeList()
        // 重置导入状态
        importFile.value = null
        importDialogVisible.value = false
      } else {
        // 显示错误信息
        if (responseData.errors && responseData.errors.length > 0) {
          const errorMsg = responseData.errors.join('\n')
          ElMessageBox.alert(errorMsg, '导入失败', {
            confirmButtonText: '确定',
            type: 'error'
          })
        } else {
          ElMessage.error(responseData.message || '导入失败')
        }
        console.error('导入返回错误:', responseData)
      }
    })
    .catch(error => {
      console.error('导入异常:', error)
      let errorMsg = '导入失败，请检查后端API是否正确配置'
      
      // 尝试提取详细错误信息
      if (error.response) {
        const status = error.response.status
        if (status === 405) {
          errorMsg = '导入失败: API方法不被允许，请确认后端接口是否正确配置 (错误码: 405)'
        } else if (status === 404) {
          errorMsg = '导入失败: API接口不存在，请确认后端接口是否正确配置 (错误码: 404)'
        } else if (status === 413) {
          errorMsg = '导入失败: 文件太大，超出服务器接受范围 (错误码: 413)'
        }
        
        if (error.response.data) {
          if (typeof error.response.data === 'string') {
            errorMsg += '\n详细信息: ' + error.response.data
          } else if (error.response.data.message) {
            errorMsg += '\n详细信息: ' + error.response.data.message
          } else if (error.response.data.detail) {
            errorMsg += '\n详细信息: ' + error.response.data.detail
          }
        }
      } else if (error.message) {
        errorMsg += '\n详细信息: ' + error.message
      }
      
      ElMessageBox.alert(errorMsg, '导入失败', {
        confirmButtonText: '确定',
        type: 'error'
      })
    })
    .finally(() => {
      importLoading.value = false
    })
}

// 处理参与提成计算值变更
const handleCommissionCalcChange = (value) => {
  // 确保存储为数字类型
  employeeForm.is_commission_calc = Number(value);
}
</script>

<style scoped>
.apple-style-container {
  padding: 0 10px 10px 10px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  background-color: #f5f5f7;
  min-height: calc(100vh - 100px);
  width: 100%;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
}

.action-section {
  margin-bottom: 24px;
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.apple-button {
  border-radius: 20px;
  height: 40px;
  padding: 0 16px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  background: rgba(0, 0, 0, 0.05);
  color: #1d1d1f;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.apple-button:hover {
  background: rgba(0, 0, 0, 0.1);
}

.apple-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.add-button {
  background: #0071e3;
  color: white;
}

.add-button:hover {
  background: #0077ed;
  opacity: 0.9;
}

.delete-button {
  background: #ff3b30;
  color: white;
}

.delete-button:hover {
  background: #ff6b5e;
  opacity: 0.9;
}

.apple-button-primary {
  background: #0071e3;
  color: white;
  border-radius: 20px;
  height: 40px;
  border: none;
  padding: 0 16px;
  transition: all 0.3s ease;
}

.apple-button-primary:hover {
  background: #0077ed;
  opacity: 0.9;
}

.apple-button-secondary {
  background: rgba(0, 0, 0, 0.05);
  color: #1d1d1f;
  border-radius: 20px;
  height: 40px;
  border: none;
  padding: 0 16px;
  transition: all 0.3s ease;
}

.apple-button-secondary:hover {
  background: rgba(0, 0, 0, 0.1);
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.stat-icon {
  width: 48px;
  height: 48px;
  background: #f5f5f7;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  color: #0071e3;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #86868b;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
}

.table-card {
  background: white;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  width: 100%;
  overflow-x: auto;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

/* 表格单元格样式 */
.id-cell {
  color: #86868b;
  font-family: monospace;
}

.username-cell {
  font-weight: 500;
  color: #1d1d1f;
}

.nickname-cell {
  font-weight: 500;
  color: #0071e3;
}

.email-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
  font-family: monospace;
  color: #666;
}

.phone-cell {
  font-family: monospace;
}

.role-tag {
  border-radius: 12px;
  padding: 2px 12px;
}

.action-button {
  margin: 0 2px;
}

/* 苹果风格的弹窗和表单样式 */
:deep(.apple-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.apple-dialog .el-dialog__header) {
  background: #f5f7fa;
  padding: 20px;
  margin: 0;
}

:deep(.apple-dialog .el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #1d1d1f;
}

:deep(.apple-dialog .el-dialog__body) {
  padding: 24px;
}

:deep(.apple-dialog .el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

.apple-input {
  width: 100%;
}

:deep(.apple-input .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
  transition: box-shadow 0.3s ease;
}

:deep(.apple-input .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-input .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

.apple-select {
  width: 100%;
}

:deep(.apple-select .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
  transition: box-shadow 0.3s ease;
}

:deep(.apple-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-select .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

:deep(.apple-switch .el-switch__core) {
  border-radius: 20px;
  height: 24px;
}

:deep(.apple-switch.is-checked .el-switch__core) {
  background-color: #34c759;
  border-color: #34c759;
}

:deep(.apple-switch .el-switch__core .el-switch__action) {
  height: 20px;
  width: 20px;
  margin: 2px;
}

/* 详情页样式 */
.detail-card {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 12px;
}

.detail-avatar {
  width: 72px;
  height: 72px;
  background: #e0e0e0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #0071e3;
}

.detail-info {
  flex: 1;
}

.detail-name {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #1d1d1f;
}

.detail-role {
  margin-bottom: 8px;
}

.detail-descriptions {
  margin-top: 16px;
}

:deep(.detail-descriptions .el-descriptions__label) {
  width: 120px;
  color: #86868b;
}

.detail-value {
  font-weight: 500;
}

.email-value {
  font-family: monospace;
}

.import-dialog {
  height: 550px;
}

.import-container {
  padding: 16px;
  height: 100%;
}

.template-download {
  margin-bottom: 20px;
}

.upload-section {
  margin-top: 20px;
}

.import-format-container {
  height: 100%;
  padding-left: 10px;
}

.import-format-tips {
  background-color: #f5f7fa;
  border-left: 4px solid #0071e3;
  padding: 12px 16px;
  margin-bottom: 16px;
  border-radius: 8px;
  font-size: 14px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  max-height: 420px;
  overflow-y: auto;
}

.import-format-tips p {
  margin: 8px 0;
}

.import-format-tips ul {
  margin: 8px 0;
  padding-left: 20px;
}

.import-format-tips li {
  margin: 6px 0;
  line-height: 1.5;
}

.upload-box {
  width: 100%;
  margin-top: 16px;
}

.upload-status-info {
  margin-top: 16px;
}
</style>

/* 上传组件样式 */
<style>
.el-upload-dragger {
  width: 100%;
  height: 180px;
  background-color: #f5f7fa;
  border: 1px dashed #d9d9d9;
  border-radius: 16px;
  box-sizing: border-box;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.el-upload-dragger:hover {
  border-color: #0071e3;
  background-color: rgba(0, 113, 227, 0.05);
}

.el-upload-dragger .el-icon--upload {
  font-size: 48px;
  color: #0071e3;
  margin-top: 30px;
  margin-bottom: 16px;
}

.el-upload-dragger .el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.el-upload-dragger .el-upload__text em {
  color: #0071e3;
  font-style: normal;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style> 